package com.weiquan.controller;

import com.weiquan.annotation.ApiLog;
import com.weiquan.common.Result;
import com.weiquan.dto.AiDiagnosisRequest;
import com.weiquan.service.AiService;
import com.weiquan.vo.AiDiagnosisVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * AI诊断控制器
 */
@Slf4j
@RestController
@RequestMapping("/ai")
@Tag(name = "AI诊断", description = "AI智能维权诊断相关接口")
@Validated
public class AiController {

    @Autowired
    private AiService aiService;

    /**
     * 执行AI诊断
     */
    @ApiLog(value = "执行AI诊断")
    @PostMapping("/diagnosis")
    @Operation(summary = "执行AI诊断", description = "根据用户输入的问题描述进行AI智能诊断")
    public Result<AiDiagnosisVO> performDiagnosis(
            @Valid @RequestBody AiDiagnosisRequest request,
            HttpServletRequest httpRequest) {
        
        Long userId = (Long) httpRequest.getAttribute("userId");
        
        log.info("用户{}发起AI诊断请求，场景：{}", userId, request.getScenario());
        
        AiDiagnosisVO result = aiService.performDiagnosis(request, userId);
        
        return Result.success(result);
    }

    /**
     * 流式AI诊断
     */
    @GetMapping("/diagnosis/stream")
    @Operation(summary = "流式AI诊断", description = "使用Server-Sent Events进行流式AI诊断")
    public SseEmitter performStreamDiagnosis(
            @Parameter(description = "场景类型") @RequestParam Integer scenario,
            @Parameter(description = "问题描述") @RequestParam String problemDescription,
            HttpServletRequest httpRequest) {
        
        Long userId = (Long) httpRequest.getAttribute("userId");
        
        log.info("用户{}发起流式AI诊断请求，场景：{}", userId, scenario);
        
        AiDiagnosisRequest request = new AiDiagnosisRequest();
        request.setScenario(scenario);
        request.setProblemDescription(problemDescription);
        
        return aiService.performStreamDiagnosis(request, userId);
    }

    /**
     * 获取诊断历史
     */
    @ApiLog(value = "获取诊断历史")
    @GetMapping("/diagnosis/history")
    @Operation(summary = "获取诊断历史", description = "获取当前用户的AI诊断历史记录")
    public Result<List<AiDiagnosisVO>> getDiagnosisHistory(HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        List<AiDiagnosisVO> history = aiService.getDiagnosisHistory(userId);
        
        return Result.success(history);
    }

    /**
     * 获取诊断详情
     */
    @GetMapping("/diagnosis/{diagnosisId}")
    @Operation(summary = "获取诊断详情", description = "获取指定诊断记录的详细信息")
    public Result<AiDiagnosisVO> getDiagnosisDetail(
            @Parameter(description = "诊断ID") @PathVariable @NotNull Long diagnosisId,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        AiDiagnosisVO detail = aiService.getDiagnosisDetail(diagnosisId, userId);
        
        return Result.success(detail);
    }

    /**
     * 重新诊断
     */
    @ApiLog(value = "重新诊断")
    @PostMapping("/diagnosis/{diagnosisId}/re-diagnosis")
    @Operation(summary = "重新诊断", description = "基于历史诊断记录重新进行AI诊断")
    public Result<AiDiagnosisVO> reDiagnosis(
            @Parameter(description = "诊断ID") @PathVariable @NotNull Long diagnosisId,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}请求重新诊断，诊断ID：{}", userId, diagnosisId);
        
        AiDiagnosisVO result = aiService.reDiagnosis(diagnosisId, userId);
        
        return Result.success(result);
    }

    /**
     * 获取场景统计
     */
    @GetMapping("/statistics/scenarios")
    @Operation(summary = "获取场景统计", description = "获取各维权场景的统计信息")
    public Result<Object> getScenarioStatistics() {
        
        // 这里可以调用统计服务获取场景数据
        // 暂时返回模拟数据
        return Result.success("场景统计数据");
    }

    /**
     * 获取成功率统计
     */
    @GetMapping("/statistics/success-rate")
    @Operation(summary = "获取成功率统计", description = "获取各场景的平均成功率统计")
    public Result<Object> getSuccessRateStatistics() {
        
        // 这里可以调用统计服务获取成功率数据
        // 暂时返回模拟数据
        return Result.success("成功率统计数据");
    }

    /**
     * 获取相似案例
     */
    @GetMapping("/similar-cases")
    @Operation(summary = "获取相似案例", description = "根据场景获取相似的成功案例")
    public Result<Object> getSimilarCases(
            @Parameter(description = "场景类型") @RequestParam Integer scenario,
            @Parameter(description = "最小成功率") @RequestParam(defaultValue = "60") Integer minSuccessRate,
            @Parameter(description = "返回数量") @RequestParam(defaultValue = "10") Integer limit) {
        
        // 这里可以调用服务获取相似案例
        // 暂时返回模拟数据
        return Result.success("相似案例数据");
    }

    /**
     * AI对话接口
     */
    @ApiLog(value = "AI对话")
    @PostMapping("/chat")
    @Operation(summary = "AI对话", description = "与AI进行对话交流")
    public Result<String> chatWithAi(
            @Parameter(description = "对话内容") @RequestParam String message,
            @Parameter(description = "对话上下文ID") @RequestParam(required = false) String contextId,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}发起AI对话，消息：{}", userId, message);
        
        // 这里可以实现AI对话逻辑
        String response = "这是AI的回复：" + message;
        
        return Result.success(response);
    }

    /**
     * 获取AI诊断模板
     */
    @GetMapping("/diagnosis/templates")
    @Operation(summary = "获取诊断模板", description = "获取不同场景的诊断问题模板")
    public Result<Object> getDiagnosisTemplates(
            @Parameter(description = "场景类型") @RequestParam(required = false) Integer scenario) {
        
        // 返回诊断模板数据
        return Result.success("诊断模板数据");
    }

    /**
     * 保存用户反馈
     */
    @PostMapping("/diagnosis/{diagnosisId}/feedback")
    @Operation(summary = "保存用户反馈", description = "保存用户对AI诊断结果的反馈")
    public Result<Void> saveFeedback(
            @Parameter(description = "诊断ID") @PathVariable @NotNull Long diagnosisId,
            @Parameter(description = "反馈评分") @RequestParam Integer rating,
            @Parameter(description = "反馈内容") @RequestParam(required = false) String content,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}提交诊断反馈，诊断ID：{}，评分：{}", userId, diagnosisId, rating);
        
        // 这里可以实现反馈保存逻辑
        
        return Result.success();
    }
}